<html>
  <body>
    <audio id="mysound" src="kbsound.mp3"></audio>
    <button onmousedown="down('a')" onmouseup="up('a')" onclick="cli('a')">
      KEY_A
    </button>

    <button onmousedown="down('b')" onmouseup="up('b')" onclick="cli('b')">
      KEY_B
    </button>

    <script>
      let time = "";
      let lock = true;
      function down(key) {
        console.log("keydown");
        time = setInterval(() => {
          console.log(key);
          lock = false;
        }, 100);
      }
      function up() {
        console.log("keyup");
        clearTimeout(time);
        //鼠标释放时让lock异步执行，setTimeout因为异步任务，所以会放到任务队列最后执行，让click事件先执行了
        setTimeout(() => {
          lock = true;
        });
      }
      function cli(key) {
        if (lock) {
          console.log(key);
        }
        playSound();
      }

      function playSound() {
        document.getElementById("mysound").play();
      }
    </script>
  </body>
</html>
